package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.quartz.dto.CreateWorkDto;
import com.ruoyi.quartz.gs.RootObject;
import com.ruoyi.system.domain.SysVoice;
import com.ruoyi.system.service.ISysVoiceService;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: com.ruoyi.quartz.task
 * @author: Sunne
 * @date: 2024-11-21 下午2:38
 * @Description: 代码备注说明
 */
@Component
public class GsTask {
    private static final String K = "f02a5517f64e4885bbb2ad88fd98c737";
    private static final String S = "9af9c2a9acee4e22b0d7301843ad1af0";
    private static final int DEFAULT_TIMEOUT = 120000;
    private static CloseableHttpClient HTTP_CLIENT;
    @Autowired
    private ISysVoiceService sysVoiceService;

    static {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(DEFAULT_TIMEOUT).setConnectTimeout(DEFAULT_TIMEOUT)
                .setSocketTimeout(DEFAULT_TIMEOUT).build();

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(1000);
        connManager.setDefaultMaxPerRoute(100);

        HTTP_CLIENT = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connManager).build();
    }

    public static void main(String[] args) {
    }

    /**
     * 查询任务进度
     * @param idproject
     * @param idWorks
     * @return
     */
    public static RootObject Progress(String idproject, String idWorks) {

        String requestStr = "{\"idProjects\": "+idproject+",\"idWorks\":"+idWorks+"}";
        String url = "https://api.zhaoli.com/v-w-c/gateway/ve/work/status";
        return gsWork(url,requestStr);
    }

    public static CreateWorkDto createWork(String url,String sourceLang,String targetLang,String wyVoiceParam){
        JSONObject createProject = new JSONObject();
        JSONObject wyVoice = new JSONObject();
        JSONObject font_param = new JSONObject();
        createProject.put("urls",url);
        createProject.put("needChineseOcclude",1);
        createProject.put("videoInpaintLang","all");
        createProject.put("sourceLang",sourceLang);
        createProject.put("lang",targetLang);
        createProject.put("needWanyin",1);
        createProject.put("wyTaskType","FULL");
        createProject.put("wyNeedText",1);
        createProject.put("removeBgAudio",2);
        font_param.put("style","default");
        font_param.put("font_size",40);
        font_param.put("position",0.727);
        wyVoice.put("id",wyVoiceParam);
       wyVoice.put("fontParam",font_param);
       createProject.put("wyVoiceParam",wyVoice);
       String urls = "https://api.zhaoli.com/v-w-c/gateway/ve/work/free";
       return gsBaseWork(urls,createProject.toString(), CreateWorkDto.class);
    }

    public static <T> T gsBaseWork(String url, String body,Class<T> clazz){
        String bodyMd5Hex = DigestUtils.md5DigestAsHex(body.getBytes());
        String md5Hex = DigestUtils.md5DigestAsHex((bodyMd5Hex + S).getBytes());
        List<Header> headers = new ArrayList<>();
        Header header1 = new BasicHeader("AppKey", K);
        Header header2 = new BasicHeader("AppSign", md5Hex);
        headers.add(header1);
        headers.add(header2);

        StringEntity entity = new StringEntity(body, "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        HttpPost method = new HttpPost(url);
        method.setEntity(entity);
        for (Header h : headers) {
            method.setHeader(h);
        }
        try {
            HttpResponse result = HTTP_CLIENT.execute(method);
            if (result.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                method.abort();
                return null;
            }
            InputStream inStream = result.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
            String lines;
            StringBuilder stringBuilder = new StringBuilder();
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), StandardCharsets.UTF_8);
                stringBuilder.append(lines);
            }
            reader.close();
            inStream.close();
            return JSON.parseObject(stringBuilder.toString(), clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static RootObject gsWork(String url, String body){
        return gsBaseWork(url,body,RootObject.class);
    }

    /**
     * 查询TTS
     */
    public static RootObject getTTS(){
        String url = "https://api.zhaoli.com/v-w-c/gateway/ve/tts/voice/list";
        String body = "{}";
        return gsWork(url,body);
    }
}